package com.hlx.controller.user;

import com.hlx.entity.user.OrderForm;
import com.hlx.entity.user.Ticket;
import com.hlx.service.admin.TrainNumberSeatService;
import com.hlx.service.user.OrderFormService;
import com.hlx.service.user.TicketService;
import com.hlx.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/orderForm")
public class OrderController {

    @Autowired
    private OrderFormService orderFormService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private TrainNumberSeatService trainNumberSeatService;

    @DeleteMapping("/deleteOrder")
    @Transactional
    public Result<String> deleteOrderForm(String id){
        log.info("{}",id);
        Integer ticketId = orderFormService.getById(id).getTicketId();
        Ticket ticket = ticketService.getById(ticketId);
        orderFormService.removeById(id);
        ticketService.removeById(ticketId);
        trainNumberSeatService.UpdateTrainNumberSeat(ticket.getTrainId(),ticket.getDate(),ticket.getSeatType());
        return Result.success("取消订单成功！");
    }

    @PutMapping("/updateOrder/{id}")
    @Transactional
    public Result<String> updateOrderForm(@PathVariable Integer id){
        OrderForm orderForm = new OrderForm();
        orderForm.setId(id);
        orderForm.setOrderStatus(1);
        Ticket ticket = new Ticket();
        ticket.setId(orderFormService.getById(id).getTicketId());
        ticket.setPrice(ticketService.getById(ticket.getId()).getPrice());
        ticket.setStatus(1);
        if(!orderFormService.updateById(orderForm) || !ticketService.updateById(ticket)){
            return Result.error("支付失败！");
        }
        return Result.success("支付成功！");
    }
}
